<template>
  <div style="height: 100vh; display: flex;align-items: center;justify-content: center;">
    <van-loading size="24px" vertical>微信授权登录中...</van-loading>
  </div>
</template>

<script setup>
import { defineComponent,onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { wxLogin } from '../api/user';
import wx from "weixin-js-sdk";
import { getJssdkConfig } from '../api/base.js';

const route = useRoute();
const router = useRouter();

const appid = process.env.VUE_APP_WX_APPID;


onMounted(() => {
  login()
})

function login() {
  // 确保每次都刷新 token 
  const token = sessionStorage.getItem('token');
  if (!token) {
    const code = route.query.code;
    if (code) {
      console.log(1);
      wxLogin(code).then((res) => {
        console.log(res, 'res');

        sessionStorage.setItem('token', res.openid)
        localStorage.setItem('token', res.openid)
        localStorage.setItem('avatar',res.headimgurl)

        const fullPath = localStorage.getItem('fullPath');
        console.log(fullPath, 'fullPath');

        getWxConfig();

        // if (fullPath) {
        //   location.href = fullPath
        // } else {
        //   location.href = '/'
        // }
      })
    } else {
      console.log('重定向授权');

      const appid = process.env.VUE_APP_WX_APPID;
      const redirect_uri = location.href;
      const redirect_url = encodeURIComponent(redirect_uri);
      const scope = "snsapi_userinfo"; // snsapi_userinfo || snsapi_base
      let state = ''
      state = encodeURIComponent(state);
      var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_url}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
      window.location.href = url
    }
  }
}

function getWxConfig() {
  // 获取微信配置
  const url = location.href.split('#')[0];
  console.log('url',url);
  getJssdkConfig(url).then(res=>{
    console.log('getwxconfig',res)
    wx.config({
      debug: false,
      appId: res.data.appId,
      timestamp: res.data.timestamp,
      nonceStr: res.data.nonceStr,
      signature: res.data.signature,
      jsApiList: ['getLocation'] // 必填，需要使用的JS接口列表
    });
    wx.error(function(res){
      console.log('error',res)
    }) 
    wx.ready(()=>{
      console.log('ready',wx)
      // 获取地理位置
      wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function (res) {
          console.log('getLocation',res)
          const latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          const longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          const speed = res.speed; // 速度，以米/每秒计
          const accuracy = res.accuracy; // 位置精度
          localStorage.setItem('latitude',latitude)
          localStorage.setItem('longitude',longitude)
        }
      })
    })
    location.href = '/'
  })
}
</script>